

local w,h = 32,32
local ui = class.panel.create('',870,1075,100,h)

ui.buttons = {}
for a=1,1 do
    for b=1,6 do
        local x = (b-1)*(w+1)
        local y = -a*(h+1)
        local button = ui:add(class.buff_button,x,y,w,h)
        button:set_highlight([[UI\Widgets\Console\Human\CommandButton\human-activebutton.blp]])
        button:hide()
        table.insert(ui.buttons,button)
    end
end

function ui:on_button_mouse_enter(button)
    local buff = button.buff
    if buff then
        local tip = buff:get_tooltips('tip')
        button:tooltip(buff.title or buff.name,tip)
    end
end


function ui:update()
    local unit = ac.unit:localunit()
    if not unit then
        return
    end
    local list = unit._buff_list or {}
    for a,button in ipairs(ui.buttons) do
        local buff = list[a]
        button.buff = buff
        if buff then
            button:refresh(buff)
            button:show()
        else
            button:hide()
        end
    end
end

ac.hardware:event '界面绘制'(function()
    ui:update()
end)

--重新排序buff内容 增益。负面.免疫，
local class_id = {
    ['增益'] = 1,
    ['负面'] = 2,
    ['免疫'] = 3
}
local sort_buff = function(list)
    table.sort(list,function(a,b)
        return (class_id[a.class] or 0)<(class_id[b.class] or 0)
    end)
end

ac.game:event '单位-获得状态'(function(_,hero,buff)
    if not buff.art then
        return
    end
    if buff.class=='增益' then
        hero:add('增益数量',1)
    elseif buff.class=='负面' then
        hero:add('负面数量',1)
    end
    if not hero._buff_list then
        hero._buff_list = {}
    end
    
    table.insert(hero._buff_list,buff)
    sort_buff(hero._buff_list)
end)

ac.game:event '单位-失去状态'(function(_,hero,buff)
    if not buff.art then
        return
    end
    if buff.class=='增益' then
        hero:add('增益数量',-1)
    elseif buff.class=='负面' then
        hero:add('负面数量',-1)
    end
    if not hero._buff_list then
        hero._buff_list = {}
    end
    local index = table.find(hero._buff_list,buff)
    table.remove(hero._buff_list,index)
    sort_buff(hero._buff_list)

end)


return ui